package com.clippick.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import co.kr.clippick.R;

public class Utils {

	public static boolean isAndroidLowerThanICS() {
		return Build.VERSION.SDK_INT < 14 ? true : false;
	}

	/* should not be crashed by outOfMemoryError */
	public static Bitmap readBitmap(Context context, Uri uri) {
		Bitmap bm = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		AssetFileDescriptor fileDescriptor = null;
		try {
			fileDescriptor = context.getContentResolver()
					.openAssetFileDescriptor(uri, "r");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bm = BitmapFactory.decodeFileDescriptor(
						fileDescriptor.getFileDescriptor(), null, options);
				fileDescriptor.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		Matrix matrix = new Matrix();
		// rotate the Bitmap (there a problem with exif so we'll query
		// the mediaStore for orientation
		Cursor cursor = context.getContentResolver().query(uri,
				new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
				null, null, null);
		if (cursor.getCount() == 1) {
			cursor.moveToFirst();
			int orientation = cursor.getInt(0);
			matrix.preRotate(orientation);
			Log.i("orientation", orientation + "");
			bm = Utils.rotateBitmap(bm, orientation);
		}
		return bm;
	}

	public synchronized static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
		if (degrees != 0 && bitmap != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) bitmap.getWidth() / 2,
					(float) bitmap.getHeight() / 2);
			try {
				Bitmap b2 = Bitmap.createBitmap(bitmap, 0, 0,
						bitmap.getWidth(), bitmap.getHeight(), m, true);
				if (bitmap != b2) {
					bitmap.recycle();
					bitmap = b2;
				}
			} catch (OutOfMemoryError ex) {
				// We have no memory to rotate. Return the original bitmap.
				Log.e("memory", "OutOfMemoryError");
			}
		}

		return bitmap;
	}

	// animation view
	public static void scaleUpFadeOutAnimation(Context mContext, View v) {
		Animation animation = AnimationUtils.loadAnimation(mContext,
				R.anim.scale_to_translate);
		v.startAnimation(animation);
	}

	public static void copyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/** check network is available */
	public static boolean checkNetwokState(ConnectivityManager manager) {
		NetworkInfo mobile = manager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifi = manager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo lte = manager
				.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
		NetworkInfo ethernet = manager
				.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

		boolean blte_4g = false;

		NetworkInfo netInfo = manager.getActiveNetworkInfo();
		if (lte != null)
			blte_4g = lte.isConnected();
		// if (mobile.isConnected() || wifi.isConnected() ||
		// ethernet.isConnected() || blte_4g || netInfo.isConnected()) {
		if (netInfo != null) {
			if (netInfo.isConnected()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/** download file and image to local device */
	public static String downloadFromUrl(String urlPath, String saveName,
			String saveFolder) {
		String fileName = saveFolder + File.separator + saveName + ".jpg";
		try {
			File file = new File(fileName);

			URL url = new URL(urlPath);
			URLConnection conn = url.openConnection();
			conn.connect();

			if (file.exists() && file.length() == conn.getContentLength()) {
				return fileName;
			}

			InputStream is = conn.getInputStream();

			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(4096);

			int current = 0;

			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();

			return fileName;
		} catch (Exception e) {
			return fileName;
		}

	}// downloadfromUrl

	public static String downloadFromUrl(String downURL, String savePath) {

		try {

			File file = new File(savePath);
			URL url = new URL(downURL);
			URLConnection conn = url.openConnection();
			conn.connect();

			if (file.exists() && file.length() == conn.getContentLength()) {
				Log.d("download", "file alrdy exists");
				return savePath;
			}

			InputStream is = conn.getInputStream();

			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(50);

			int current = 0;

			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			FileOutputStream fos = new FileOutputStream(file);
			// FileOutputStream fos1 = openFileOutput("logo2.gif",
			// Context.MODE_PRIVATE);
			fos.write(baf.toByteArray());
			fos.close();

			return savePath;
		} catch (Exception e) {
			String imsi = e.toString();
			return savePath;
		}
	}// downloadfromUrl
}
